package org.wyl.xiachufang.spider;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wyl.xiachufang.entity.FoodEntity;
import org.wyl.xiachufang.entity.MenuEntity;
import org.wyl.xiachufang.entity.MenuFoodEntity;
import org.wyl.xiachufang.mapper.FoodMapper;
import org.wyl.xiachufang.mapper.MenuFoodMapper;
import org.wyl.xiachufang.mapper.MenuMapper;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

/**
 * @author 吴宇亮 on 2022/7/25 16:41
 */
@Component
public class FoodPipeline implements Pipeline {

    @Autowired
    private FoodMapper foodMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private MenuFoodMapper menuFoodMapper;

    @Override
    public void process(ResultItems resultItems, Task task) {
        Boolean isVaild = resultItems.get("isVaild");
        if(isVaild){
            List<FoodEntity> foodEntities = resultItems.get("foodEntities");
            List<MenuEntity> menuEntities = resultItems.get("menuEntities");
            List<MenuFoodEntity> menuFoodEntities = resultItems.get("menuFoodEntities");

            for (FoodEntity foodEntity : foodEntities) {
                FoodEntity oldEntity = foodMapper.selectById(foodEntity.getFoodName());
                if(null == oldEntity){
                    foodMapper.insert(foodEntity);
                }
            }

            for (MenuEntity menuEntity : menuEntities) {
                MenuEntity oldEntity = menuMapper.selectById(menuEntity.getMenuName());
                if(null == oldEntity){
                    menuMapper.insert(menuEntity);
                    // 保存图片
                    String memuImageSrc = resultItems.get("memuImageSrc");
                    if(StrUtil.isNotBlank(memuImageSrc)){
                        HttpUtil.downloadFile(memuImageSrc, "E:\\temp\\menu\\" + menuEntity.getMenuName() + ".jpg");
                    }
                }
            }

            for (MenuFoodEntity menuFoodEntity : menuFoodEntities) {
                QueryWrapper<MenuFoodEntity> queryWrapper = new QueryWrapper<MenuFoodEntity>()
                        .eq("menu_name", menuFoodEntity.getMenuName())
                        .eq("food_name", menuFoodEntity.getFoodName());
                Long count = menuFoodMapper.selectCount(queryWrapper);
                if(count == 0){
                    menuFoodMapper.insert(menuFoodEntity);
                }
            }
        }
    }
}



























